package com.zeyuan.rpcclient.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false); //切换到非阻塞模式，如果没有连接，accept不会阻塞，会返回null，read也非阻塞继续运行并返回0
        ByteBuffer bf=ByteBuffer.allocate(100);
        ssc.bind(new InetSocketAddress(8888));
        System.out.println("connected");
        List<SocketChannel> channels=new ArrayList<>();
        while (true){
            System.out.println("start");
            SocketChannel channel = ssc.accept(); //阻塞，会让线程暂停，直到客户端连接，有连接状态的socket发起事件
            System.out.println("accepted");
            channels.add(channel);

            for(SocketChannel s:channels){
                System.out.println("before read");
                s.read(bf);//阻塞，直到发入数据
                bf.flip();
                bf.clear();
            }
            System.out.println("finished");
        }
    }
}
